import O1HD from "../gameEngine";
import { FileKind } from "./FileKind";
import ParseCSV from "./ParseCSV";

export default class utilsModel {

     /**
      * 读取csv文件
      * @param bundle 
      * @param filename 
      * @param func 
      * @returns 
      */
    static async readCsvData(bundle: cc.AssetManager.Bundle, filename: string, func?: (array: any)=> void){
        return new Promise<any>(resolve => {
            bundle = bundle || cc.resources;
            bundle.load(filename, function (err, string) {
                if (err) {
                    console.error(`csv读取错误 filename = ${filename}  `, err.message || err);
                    resolve(null);
                    return;
                }
    
                // cc.log("read finish ", string.toString());
                
                let array = ParseCSV.csvToArray(string.toString())
    
                cc.assetManager.releaseAsset(string);
                
                // cc.log('arr ', array);
                if (func) {
                    func(array)
                }
                resolve(array);
            });
        });
    }

    /**
     * 解析csv数据
     * @param array 
     * @param bFirstMap 
     * @returns 
     */
    static parseCsvData(array: any, bFirstMap: boolean = false) {
        let data = {};
        data['title'] = {}
            
        for (let i in array[1]){
            data['title'][array[1][i]] = i;
        }

        let idIndex = data['title'].id ?? 0;
        for(let i = 2; i < array.length; i++){
            if (bFirstMap) {
                if (!data[array[i][idIndex]]) {
                    data[array[i][idIndex]] = [];
                }
                data[array[i][idIndex]].push(array[i]);
            } else {
                data[array[i][idIndex]] = array[i];
            }
            
        }
        return data;
    }
    
    static transCsvDataLine(csvData: any, id: string): any {
        let _title = csvData.title;
        let info = csvData[id];
        if (!info) {
            return null;
        }
        let result = {};
        for (let n in _title) {
            result[n] = info[_title[n]];
        }
        return result;
    }
    
    /**
     * 是否有效数值
     * @param value 
     */
    static isValidNumberValue(value: number | string) {
        if (value == undefined || value == null 
            || value == -1
        ) {
            return false;
        }
        if (typeof value == 'number' && isNaN(value)) {
            return false;
        }  
        if (typeof value == 'string' && value == '') {
            return false;
        }
        return true;
    }

    /**
     * 获取json数据长度
     * @param jsonData 
     */
    static getJsonDataLength(jsonData: any) {
        if (!jsonData) {
            return 0;
        }

        let count = 0;
        for (let i in jsonData) {
            count++;
        }
        return count;
    }

    /** 是否在观看广告中 */
    static bLookAding = false;
    /**
     * 加载并显示视频广告
     * @param successCallback 成功回调
     * @param errorCallback 失败回调
     * @param completeCallback 完成回调
     * @param reportAnalyticsExplain 成功上报描述
     */
    static loadAndShowVideoAdTrans(
        successCallback: () => void,
        errorCallback: (error: any) => void,
        completeCallback?: () => void,
        reportAnalyticsExplain?: string
    ): void 
    {
        if (this.bLookAding) {
            console.log('重复点击广告');
            return;
        }
        this.bLookAding = true;
        O1HD.getServices().miniGameSrv.getAppApiInstance().loadAndShowVideoAd(
            ()=> {
                this.bLookAding = false;
                if (successCallback) {
                    successCallback();
                }
            }
            , (error)=> {
                this.bLookAding = false;
                if (errorCallback) {
                    errorCallback(error);
                }
            }
            , ()=> {
                this.bLookAding = false;
                if (completeCallback) {
                    completeCallback();
                }
            }
            , reportAnalyticsExplain
        );
    }

    static splitLineFeed(strParse: string) {
        let splitType = FileKind.ResParseType.BIG_ITEM;
        if (!strParse.includes(splitType)) {
            splitType = FileKind.ResParseType.BIG_ITEM2;
        }
        return strParse.split(splitType);
    }

}

